package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 获取地址类
 *
 * @author ruoyi
 */
public class AddressUtils {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    //public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";

    public static final String IP_URL = "http://ip-api.com/json/ipaddress?lang=zh-CN";

    public static String getRealAddressByIP(String ip) {
        String address = "XX XX";
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        if (RuoYiConfig.isAddressEnabled()) {
            String ips = IP_URL.replace("ipaddress", ip);
            String rspStr = getResult(IP_URL.replace("ipaddress", ip), "utf-8");
            if (StringUtils.isEmpty(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return address;
            }
            // JSONObject obj = JSONObject.parseObject(rspStr);
            // JSONObject data = obj.getObject("data", JSONObject.class);
            // String region = data.getString("region");
            // String city = data.getString("city");
            // address = region + " " + city;
            StringBuilder sb = new StringBuilder();
            JSONObject country = JSON.parseObject(rspStr);
            System.out.println(country);
            if (StringUtils.isEmpty(country.getString("country"))  || !country.getString("country").equals("")) {
                sb.append(country.getString("country") + " ");
            }
            if (StringUtils.isEmpty(country.getString("regionName")) || !country.getString("regionName").equals("")) {
                sb.append(country.getString("regionName") + " ");
            }
            if (StringUtils.isEmpty(country.getString("city")) || !country.getString("city").equals("")) {
                sb.append(country.getString("city"));
            }
            address = sb.toString();
        }
        return address;
    }


    private static String getResult(String urlStr, String encoding) {
        URL url = null;
        HttpURLConnection connection = null;
        try {
            url = new URL(urlStr);
            // 新建连接实例
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接超时时间，单位毫秒
            connection.setConnectTimeout(8000);
            // 设置读取数据超时时间，单位毫秒
            connection.setReadTimeout(8000);
            // 是否打开输出流 true|false
            connection.setDoOutput(true);
            // 是否打开输入流true|false
            connection.setDoInput(true);
            // 提交方法POST|GET
            connection.setRequestMethod("POST");
            // 是否缓存true|false
            connection.setUseCaches(false);
            connection.connect();// 打开连接端口
            // 往对端写完数据对端服务器返回数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), encoding));
            // ,以BufferedReader流来读取
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();// 关闭连接
            }
        }
        return null;
    }
}
